<style type="text/css">
	#form-content legend { display: none; }
	#user-list .form-entry input {
		width: 100px;
	}
	#user-list th { font-weight: bold; background: #efefef; padding: 5px; }
</style>
<div id="header" style="display:none;">
<h1 style="margin-top:3px;letter-spacing:0.1em;text-transform:uppercase; padding-left:10px;"><img src="templates/builder/images/logo.png" style="margin-top: -7px;" height="24" align="absmiddle" /> Prails IDE</h1>
</div>
<div id="help" style="display:none;">
	<div style="padding:10px;width:400px;">
		<h1>Prails IDE - Online Help</h1>
		<p style="font-size:10px;color: #999;">
		  Version: <b><?=FRAMEWORK_VERSION?></b>
		  <? if ($arr_param["local"]["changeset"]) { ?>
		      <div style="background-color: #FFA;border: 1px solid #CC6;font-size: 10px;padding: 5px;text-align: center;">Prails #local.version is available now! See <a href="javascript:" onclick="showChangeSet();return false;">what's new</a>. You can <a href="javascript:" onclick="runSelfUpdate();return false;">update here</a>.</div>
		      <div style="display: none;" id="changesetText">
		          <pre style="white-space:pre-wrap;padding:10px;"><?=htmlspecialchars($arr_param["local"]["changeset"])?></pre>
		      </div>
		  <? } ?>
		</p>
		<p>Welcome to the Prails Framework. On the left hand side you can see your personal navigation area. Under "Modules" you can see all modules that do exist.
		By double clicking an entry you edit this module. By right clicking you can change the module's options. </p>
		<p>When editing a module, your navigation area will let you see the event handlers and data queries of the current module. By double-clicking either of them you 
		can edit it.</p>
		<br/><h2>Short Cuts:</h2>
		<table>
			<tr><td>move one tab left</td><td>Ctrl+Alt+Left</td></tr>
			<tr><td>move one tab right</td><td>Ctrl+Alt+Right</td></tr>
			<tr><td>close current tab</td><td>Ctrl+Shift+Q</td></tr>
			<tr><td>execute event / sql query</td><td>Ctrl+Shift+X</td></tr>
			<tr><td>open item...</td><td>Ctrl+Shift+D</td></tr>
			<tr><td>sql query tab</td><td>Ctrl+Shift+A</td></tr>
			<tr><td>save current item</td><td>Ctrl+S</td></tr>
			<tr><td>search/replace in code</td><td>Ctrl+F</td></tr>
		</table>
		<br/>
		<h2>Futher help:</h2>
		<ul style="list-style-type: list;">
			<li><a href="api/index.html" target="_api">API Documentation</a></li>
			<li><a href="javascript:(function(){var s=document.createElement('script');s.src='templates/builder/js/langhelper.js';document.body.appendChild(s);})();">CMS Helper Bookmarklet</a></li>
		</ul>
	</div>
</div>
<div id="export_panel" style="display: none;">
	<div style="padding: 10px;">
	<form method="post" action="?event=builder:export">
		<fieldset>
			<legend>Modules:</legend>
			<select class="export" name="modules[]" multiple="multiple" size="5" id="modules">
				<c:foreach var="modules" name="module">
					<option selected="selected" value="#module.module_id">#module.name</option>
				</c:foreach>
			</select>
			<div>
				<a href="javascript:" onclick="$$('#modules option').each(function(item){item.selected=true;});">select all</a> | 
				<a href="javascript:" onclick="$$('#modules option').each(function(item){item.selected=false;});">select none</a>
			</div>
		</fieldset>
		<fieldset>
			<legend>Libraries:</legend>
			<select class="export" name="libraries[]" multiple="multiple" size="5" id="libraries">
				<c:foreach var="libraries" name="library">
					<option selected="selected" value="#library.library_id">#library.name</option>
				</c:foreach>
			</select>
			<div>
				<a href="javascript:" onclick="$$('#libraries option').each(function(item){item.selected=true;});">select all</a> | 
				<a href="javascript:" onclick="$$('#libraries option').each(function(item){item.selected=false;});">select none</a>
			</div>
		</fieldset>
		<fieldset>
			<legend>Tags:</legend>
			<select class="export" name="tags[]" multiple="multiple" size="5" id="tags">
				<c:foreach var="tags" name="tag">
					<option selected="selected" value="#tag.tag_id">#tag.name</option>
				</c:foreach>
			</select>
			<div>
				<a href="javascript:" onclick="$$('#tags option').each(function(item){item.selected=true;});">select all</a> | 
				<a href="javascript:" onclick="$$('#tags option').each(function(item){item.selected=false;});">select none</a>
			</div>
		</fieldset>		
		<fieldset>
			<legend>Tables:</legend>
			<select class="export" name="tables[]" multiple="multiple" size="5" id="tables" style="height: 98px;">
				<c:foreach var="tables" name="table">
					<option selected="selected" value="#table.table_id">#table.name</option>
				</c:foreach>
			</select>
			<div>
				<a href="javascript:" onclick="$$('#tables option').each(function(item){item.selected=true;});">select all</a> | 
				<a href="javascript:" onclick="$$('#tables option').each(function(item){item.selected=false;});">select none</a>
			</div>
		</fieldset>
		<fieldset>
			<legend>Content Assets:</legend>
			<select class="export" name="translations[]" multiple="multiple" size="5" id="translations">
				<c:foreach var="texts" name="text" key="root">
					<option selected="selected" value="#local.root">#local.root</option>
				</c:foreach>				
			</select>
			<div>
				<a href="javascript:" onclick="$$('#translations option').each(function(item){item.selected=true;});">select all</a> | 
				<a href="javascript:" onclick="$$('#translations option').each(function(item){item.selected=false;});">select none</a>
			</div>
			<div style="margin-top: 10px;">
				<input type="checkbox" name="images" value="1" checked="checked" id="export-images"/>
				<label for="export-images" onclick="this.previous().checked = !this.previous().checked;">include images</label>
			</div>
		</fieldset>
		<fieldset>
			<legend>Database Content:</legend>
			<select class="export" name="db[]" multiple="multiple" size="5" id="dbs" style="height:98px;">
				<c:foreach var="tables" name="table">
					<option value="#table.name">#table.name</option>
				</c:foreach>
			</select>
			<div>
				<a href="javascript:" onclick="$$('#dbs option').each(function(item){item.selected=true;});">select all</a> | 
				<a href="javascript:" onclick="$$('#dbs option').each(function(item){item.selected=false;});">select none</a>
			</div>			
		</fieldset>
		<div class="panel-bottom"> Save to:
		<input type="text" name="file" value="<?=preg_replace('/[^a-zA-Z0-9_.]/', '_', PROJECT_NAME)."-".date("Y-m-d").".prails"?>" />
		<button type="submit">export</button>
		</div>
	</form>
	</div>
</div>
<div id="import_panel" style="display: none;"><!--
	<div style="padding: 10px;">
	<fieldset>
		<legend>
			File to import: 
		</legend>
		<qw:file 	
			target="?event=builder:import&name=" 
			progress="progress" 
			onstart="$('currentFile').innerHTML='Uploading '+this.fileName+' ('+Math.round(this.fileSize / 1024)+'kB)...';" 
			ondone="location.reload();"
		>
			<button>Click to upload</button>
		</qw:file>
		<div id="currentFile"></div>
		<div style="position:relative;width:200px;height:10px;border:1px solid #ccc;background-color:#fff;display:none;">
			<div id="progress" style="position:absolute;left:0px;top:0px;height:100%;width:0px;background-color:#cf9;border-right:1px solid #ccc;"></div>
		</div>
		
		<p style="margin: 1em 0px;"><i>Please note:</i> you can only upload package files to a maximum size of <b><?=ini_get("post_max_size")?>B</b> each.</p>	
	</fieldset>
	<c:if cond="ENV_PRODUCTION === true">
	<form method="post" action="?event=builder:restore" id="restoreForm" onsubmit="return restoreDB();">
	<fieldset style="width:382px;">
		<legend>Restore Backup</legend>
		<p>Please select the backup file you want to restore.</p>
		<select name="file" size="6" style="width: 100%;">
			<c:foreach var="backupList" name="item">
				<option value="<%=$item%>"><%=$item%></option>
			</c:foreach>
		</select>
		<input type="checkbox" name="dataRestore" value="1" id="dtRestore" /> <label for="dtRestore">also restore database contents</label>
		<div class="panel-bottom"> Restore Procedure:
		<button type="submit">Start</button></div>
	</fieldset>
	</form>
	</c:if>
	</div>
--></div>
<div id="library_upload_panel"><!-- <div style="padding: 10px;">
	<fieldset>
		<legend>
			Library to import: 
		</legend>
		<qw:file 	
			target="?event=builder:editLibrary&library_id=0&import=1&name=" 
			progress="progress" 
			onstart="$('currentFile').innerHTML='Uploading '+this.fileName+' ('+Math.round(this.fileSize / 1024)+'kB)...';" 
			ondone="loadURL('?event=builder:home&open_nav=qwbuilder_libsPanel');"
		>
			<button>Click to upload</button>
		</qw:file>
		<div id="currentFile"></div>
		<div style="position:relative;width:200px;height:10px;border:1px solid #ccc;background-color:#fff;display:none;">
			<div id="progress" style="position:absolute;left:0px;top:0px;height:100%;width:0px;background-color:#cf9;border-right:1px solid #ccc;"></div>
		</div>
		
		<p style="margin: 1em 0px;"><i>Please note:</i> you can only upload libraries to a maximum size of <b><?=ini_get("post_max_size")?>B</b> each.</p>
		<p style="margin: 1em 0px;">For complex libraries it is recommended to upload the library archive in it's original packed format (.tar.gz, .tar.bz2 or .zip).</p>	
	</fieldset>
	</div>
 --></div>
<c:if cond="ENV_PRODUCTION === true">
<div id="replicate_panel" style="display: none;"><!--
	<div style="padding: 10px;">
		<h2>Replication</h2>
		<fieldset id="connection_details">
			<legend>Source Instance</legend>
			<p>Replication enables you to copy over features you select from one instance over to this one. Therefore, please enter the URL and credentials of the instance you want to replicate from. After successful connection, you can select the features to replicate.<br/><br/></p>
			<c:input type="text" name="replicate[source]" value="" label="URL to source instance:" />
			<c:input type="text" name="replicate[source_user]" value="" label="Remote user:" />
			<c:input type="password" name="replicate[source_pass]" value="" label="Remote password:" />
			<% /* need to do proxied HTTP request as source could be hosted somewhere else */ %>
			<button type="button" onclick="Replication.connect(this.up().select('input'));">Connect</button>
		</fieldset>
		<div id="replication_details" style="display:none;">
		<% /* code replication settings */ %>
			<fieldset>
				<legend>Remote Modules:</legend>
				<select class="export" name="modules[]" multiple="multiple" size="5" id="repl_modules">
				</select>
				<div>
					<a href="javascript:" onclick="$$('#repl_modules option').each(function(item){item.selected=true;});">select all</a> | 
					<a href="javascript:" onclick="$$('#repl_modules option').each(function(item){item.selected=false;});">select none</a>
				</div>
			</fieldset>
			<fieldset>
				<legend>Remote Libraries:</legend>
				<select class="export" name="libraries[]" multiple="multiple" size="5" id="repl_libraries">
				</select>
				<div>
					<a href="javascript:" onclick="$$('#repl_libraries option').each(function(item){item.selected=true;});">select all</a> | 
					<a href="javascript:" onclick="$$('#repl_libraries option').each(function(item){item.selected=false;});">select none</a>
				</div>
			</fieldset>
			<fieldset>
				<legend>Remote Tags:</legend>
				<select class="export" name="tags[]" multiple="multiple" size="5" id="repl_tags">
				</select>
				<div>
					<a href="javascript:" onclick="$$('#repl_tags option').each(function(item){item.selected=true;});">select all</a> | 
					<a href="javascript:" onclick="$$('#repl_tags option').each(function(item){item.selected=false;});">select none</a>
				</div>
			</fieldset>		

			<% /* Data replication settings */ %>
			<fieldset>
				<legend>Remote Tables:</legend>
				<select class="export" name="tables[]" multiple="multiple" size="5" id="repl_tables" style="height: 98px;">
				</select>
				<div>
					<a href="javascript:" onclick="$$('#repl_tables option').each(function(item){item.selected=true;});">select all</a> | 
					<a href="javascript:" onclick="$$('#repl_tables option').each(function(item){item.selected=false;});">select none</a>
				</div>
			</fieldset>
			<fieldset>
				<legend>Remote Content:</legend>
				<select class="export" name="translations[]" multiple="multiple" size="5" id="repl_translations">
				</select>
				<div>
					<a href="javascript:" onclick="$$('#repl_translations option').each(function(item){item.selected=true;});">select all</a> | 
					<a href="javascript:" onclick="$$('#repl_translations option').each(function(item){item.selected=false;});">select none</a>
				</div>
				<div style="margin-top: 10px;">
					<input type="checkbox" name="images" value="1" checked="checked" id="repl_export-images"/>
					<label for="export-images" onclick="this.previous().checked = !this.previous().checked;">include images</label>
				</div>
			</fieldset>
			<div class="panel-bottom">
				<button type="button" onclick="Replication.start($('replication_details').select('select, input'));">Start Replication</button>
			</div>
		</div>
	</div> 
--></div>
</c:if>
<div id="backup_panel" style="display: none;"><!-- 
	<div style="padding: 10px;">
		<h2>Schedule Backups</h2>
		<p>Please select the timing when a backup should be running regularily.</p>
		<div class="scheduler" style="border: 1px solid #ccc;margin-top: 10px;">
			<form method="post" action="?event=builder:backup&save=1" onsubmit="convertScheduleDataToJSON(this); return false;">
			<input type="hidden" name="backupTime" value="" id="backupTime"/>
			<div class="form-entry repeat">
				<div class="label">
					<label for="from">Every:</label>
				</div>
				<div class="value">
					<input type="text" name="repeat" value="0" />
					<select name="type" size="1">
						<option value="mins">Minutes</option>
						<option value="hours">Hours</option>
						<option value="days" selected="selected">Days</option>
						<option value="months">Months</option>						
					</select>
				</div>
			</div>
			<div class="form-entry days">
				<div class="label">
					<label for="from">On these days:</label>
				</div>
				<div class="value radiogroup">
					<div class="radio">
						<input type="checkbox" name="weekday[mon]" value="1" checked="checked" id="mon_b" /> 
						<label for="mon_b">Monday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[tue]" value="2" checked="checked" id="tue_b" /> 
						<label for="tue_b">Tuesday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[wed]" value="3" checked="checked" id="wed_b" /> 
						<label for="wed_b">Wednesday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[thu]" value="4" checked="checked" id="thu_b" /> 
						<label for="thu_b">Thursday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[fri]" value="5" checked="checked" id="fri_b" /> 
						<label for="fri_b">Friday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[sat]" value="6" checked="checked" id="sat_b" /> 
						<label for="sat_b">Saturday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[sun]" value="0" checked="checked" id="sun_b" /> 
						<label for="sun_b">Sunday</label>
					</div>
				</div>
			</div>
			<div class="panel-bottom">
				<button type="button" onclick="backupNow();" style="float:left;">Backup now</button>
				<button type="submit" name="save">Save</button>
			</div>
			</form>
		</div>		
	</div> -->
</div>
<div id="searchReplaceForm" style="display:none;">
	<div class="searchReplaceForm">
		<div class="form-entry">
			<label for="tosearch">Find:</label>
			<input type="text" name="tosearch" id="tosearch" value="" /> <!-- probably make this a combo box -->
		</div>
		<div class="form-entry">
			<label for="toreplace">Replace with:</label>
			<input type="text" name="toreplace" id="toreplace" value=""/>
		</div>
		<fieldset>
			<legend>Direction</legend>
			<div class="form-entry radiobox">
				<div class="radio">
					<input type="radio" name="dir" value="0" id="forward" checked="checked"/><label for="forward">Forward</label>
				</div>
				<div class="radio">
					<input type="radio" name="dir" value="1" id="backward"/><label for="backward">Backward</label>
				</div>
			</div>
		</fieldset>
		<fieldset>
			<legend>Options</legend>
			<div class="form-entry radiobox">
				<div class="radio">
					<input type="checkbox" name="regexp" value="1" id="regexp"/><label for="regexp">Regular Expression</label>
				</div>
				<div class="radio">
					<input type="checkbox" name="regexp" value="1" checked="checked" id="wrapsearch"/><label for="wrapsearch">Wrap search</label>
				</div>
			</div>
		</fieldset>
	</div>	
</div>
<div id="shoutbox" style="display:none;">
	<div style="margin-left:3px;margin-top:3px;">
	<form method="post" action="?event=builder:shout" onsubmit="try{window.dold = (new Date()).getTime();invoke('sbmsglist', 'builder:shout', this.serialize(), true);$('sbmsg').value='';$('sbmsg').blur();}catch(e){console.log(e);};return false;">
		<input type="text" name="msg" id="sbmsg" value="GURU MEDITATION" style="width:190px;" onfocus="if(this.value == 'GURU MEDITATION')this.value='';" />
		<input type="image" src="templates/builder/images/comment.png" style="margin-left:-20px;vertical-align:middle;" />
	</form></div>
	<div id="sbmsglist"></div>
</div>
<div id="usermgmt-form" style="display: none;">
	<fieldset id="my-account">
		<div style="padding: 20px;">
		<legend>My Account</legend>
		<div class="form-entry">
			<div class="label">Name:</div>
			<div class="value" style="font-style:italics;color: #666;"><?=$_SESSION["builder"]["name"]?></div>
		</div>
		<div class="form-entry">
			<div class="label">User Group:</div>
			<div class="value" style="font-style:italics;color: #666;"><?=$_SESSION["builder"]["group"]?></div>
		</div>
		<c:input name="user[password]" value="" type="password" class="required" label="Password:"/>
		<c:input name="user[password2]" value="" type="password" class="required" rel="this.value == document.getElementsByName('user[password]')[0].value" label="Re-type Password:"/>
		</div>	
	</fieldset>
</div>

<script type="text/javascript">
	//<![CDATA[
	var win;
	var schedule = JSON.parse('<?=json_encode($arr_param["backup"])?>');
	Ext.BLANK_IMAGE_URL = (function() {
		if (Ext.isIE8 || Ext.isGecko || Ext.isOpera || Ext.isWebkit) {
			return "";
		} else {
			return "templates/builder/images/default/s.gif";
		}			
	})();
	
	var backupNow = function() {
		window._backupProgress = Ext.MessageBox.show({
			title: 'Please wait',
			msg: 'Running backup',
			progressText: 'Backing up system',
			width: 300,
			progress: true,
			closable: false
		});
		window._backupProgress.pe = new PeriodicalExecuter(function(pe) {
			if (!pe.frames) pe.frames = 0;
			window._backupProgress.updateProgress((pe.frames % 100) / 100.0, window._backupProgress.currentStatus);
			pe.frames++;
		}, 0.1);
		invoke(null, 'builder:backup', null, false, function(req){
			window._backupProgress.hide();
			Ext.Msg.alert('Info', 'Backup complete', function(){
				location.reload();
			});
		});	
	}
	
	var restoreDB = function() {
		if($('restoreForm').down('select').value.empty()) {
			Ext.Msg.alert('Problem', 'Please select a backup file to restore.');
			return false;
		}
		if($('dtRestore').checked) {
			try{
				Ext.Msg.confirm('Warning!', 'Do you really want to remove all database content and re-import it from the backup?', function(btn) {
					if (btn == 'yes') {
						window._restoreProgress = Ext.MessageBox.show({
							title: 'Please wait',
							msg: 'Running restoration',
							progressText: 'Restoring system',
							width: 300,
							progress: true,
							closable: false
						});
						window._restoreProgress.pe = new PeriodicalExecuter(function(pe) {
							if (!pe.frames) pe.frames = 0;
							window._restoreProgress.updateProgress((pe.frames % 100) / 100.0, window._restoreProgress.currentStatus);
							pe.frames++;
						}, 0.1);
						new Ajax.Request($('restoreForm').action, {
				            method: "POST",
				            parameters: $("restoreForm").serialize(), 
							onSuccess: function(req){
								window._restoreProgress.hide();
								Ext.Msg.alert('Info', 'Restoration complete', function(){
									location.reload();
								});
							}
						});	
					}
				});
			} catch(e) {
				console.log(e);
			};
			return false;
		}		
	}
	
	var convertScheduleDataToJSON = function(form) {
		var repeat = $$(".scheduler .repeat input")[0].value;
		var repInt = $$(".scheduler .repeat select")[0].value;
		var days = $$(".scheduler .days input");
		var dlist = [];
		var time = "0:0";
		var date = "<?=date('Y-m-d')?>";
		days.each(function(d){
			if (d.checked) {
				dlist.push(d.value);
			}
		});
		
		var crontab = {
			min: (repInt == 'mins' ? "*/"+repeat : time.split(":")[1]),
			hour: (repInt == 'hours' ? "*/"+repeat : time.split(":")[0]),
			day: (repInt == 'days' ? "*/"+repeat : date.split("-")[2]),
			month: (repInt == 'months' ? "*/"+repeat : date.split("-")[1]),
			week: dlist.join(","),
			time: time,
			date: date								
		};
		
		$("backupTime").value = JSON.stringify(crontab);
		form.submit();	
	};
	
	var updateProgress = function(url, msg) {
	    window._prailsInstallProgress.currentStatus = msg;
        new Ajax.Request(url, {
            method: "GET",
            onSuccess: function(req) {
                if (req.responseText.replace(/^\s*/gi, "").indexOf("success") == 0) {
                    if (req.responseText.split("\n")[1] != "--") {
                        updateProgress(req.responseText.split("\n")[1], req.responseText.split("\n")[2]);
                    } else {
	 	    			window._prailsInstallProgress.pe.stop();
                        window._prailsInstallProgress.hide();
                        if ((warns = req.responseText.split("\n")[2]).length > 0) {
                            Ext.MessageBox.alert("Completed", "The installation of Prails Version <?=trim($arr_param['local']['version'])?> finished with warnings: <br/>"+warns, function() {
                                location.reload();
                            });                            
                        } else {
                            Ext.MessageBox.alert("Completed", "The installation of Prails Version <?=trim($arr_param['local']['version'])?> is complete.", function() {
                                location.reload();
                            });
                        }
                    }
                } else {
                    window._prailsInstallProgress.hide();
	 	    		window._prailsInstallProgress.pe.stop();
                    Ext.MessageBox.alert("Error", req.responseText);
                }
            }
        });
	};
	
	var showUserMgmt = function(content, title) {
		if (!title) title = "Edit Account";
		if (!content) content = $("usermgmt-form").down('#my-account').innerHTML;
		if (window.userMgmt) window.userMgmt.hide();
		var buttons = [];
		
		buttons.push({
			text: "Save",
			handler: function() {
				// send ajax call to store in file
				var items = "";
				$$("#form-content input, #form-content select").each(function(item) {
					items += "&"+item.serialize();
				});
				invoke(null, "builder:editUser", items, true, function(req){
					Ext.ux.util.msg("Changes saved", "Your new password has been set successfully.");
					window.userMgmt.close();
				});
			}
		});
		buttons.push({
			text: "Cancel",
			handler: function() {
				window.userMgmt.hide();
			}
		});
		
		window.userMgmt = new Ext.Window({
			layout: "fit",
			title: title,
			width: 400,
			height: 300,
			plain: true,
			items: new Ext.Panel({
				deferredRender: false,
				autoScroll: true,
				border: false,
				id: "form-content",
				html: content
			}),
			buttons: buttons
		});
		window.userMgmt.show(this);
	};
	
	var runSelfUpdate = function() {
	   if (window.changeSetWindow) {
            window.changeSetWindow.hide();
	   }
        window._prailsInstallProgress = Ext.MessageBox.show({
            title: 'Please wait',
            msg: 'Updating Prails',
            progressText: 'Downloading...',
            width: 300,
            progress: true,
            closable: false
        });
        window._prailsInstallProgress.currentStatus = "Downloading...";
        window._prailsInstallProgress.pe = new PeriodicalExecuter(function(pe) {
            if (!pe.frames) pe.frames = 0;
            window._prailsInstallProgress.updateProgress((pe.frames % 100) / 100.0, window._prailsInstallProgress.currentStatus);                        
            pe.frames++;
        }, 0.1);
        // send update request to server
        updateProgress("?event=builder:updateSystem", "Downloading installer...");
	};
	
	var showChangeSet = function() {
        window.changeSetWindow = new Ext.Window({
            layout:'fit',
            title: "Changes in <?=trim($arr_param['local']['version'])?>",
            width:500,
            height:300,
            plain: true,

            items: new Ext.Panel({
                html: $("changesetText").innerHTML,
                deferredRender:false,
                autoScroll: true,
                border:false
            }),

            buttons: [{
                text: "Update",
                handler: runSelfUpdate
            }, {
                text: 'Close',
                handler: function(){
                    window.changeSetWindow.hide();
                }
            }]
        });
        window.changeSetWindow.show(this);
	};
	
	Ext.onReady(function() {
		Ext.BLANK_IMAGE_URL = (function() {
			if (Ext.isIE8 || Ext.isGecko || Ext.isOpera || Ext.isWebkit) {
				return "";
			} else {
				return "templates/builder/images/default/s.gif";
			}			
		})();
		
		window.dold = 0;
		window.firstCall = true;
		window.detag = "";
		window.uid = "<?=$_SESSION['builder']['user_id']?>";
		window.testsuites = [{
			checked: true,
			id: "all",
			text: "All Testcases"
		}];
		window.logs = [];
		window.searchReplaceForm = $("searchReplaceForm").cloneNode(true);
		$("searchReplaceForm").remove();
		
		new PeriodicalExecuter(function(pe) {
			if (window.testStarted) {
				if (Ext.getCmp("testresult").initialConfig.iconCls != "testRunning") {
					Ext.getCmp("testresult").setIconClass("testRunning");
				} else {
					if (window.success > 0) {
						Ext.getCmp("testresult").setIconClass("testSuccess");
					} else {
						Ext.getCmp("testresult").setIconClass("testUnknown")
					}
				}
			} else {
				if (window.errors > 0) {
					Ext.getCmp("testresult").setIconClass("testError");
				} else if (window.success > 0) {
					Ext.getCmp("testresult").setIconClass("testSuccess");
				} else {
					Ext.getCmp("testresult").setIconClass("testUnknown")	
				}
			}
			if (window.testLog) {
				$$(".testLog").each(function(item) {
					item.innerHTML = testLog.join("");
				});
			}
		}, 0.5);
		
		<? if (DEVELOPER_CHAT_ENABLED) { ?>
		new PeriodicalExecuter(function(pe){
			new Ajax.Updater("sbmsglist", "shout.box", {
				method: "get",
				requestHeaders: {
					"If-Modified-Since": (new Date(window.dold)).toGMTString(),
					"If-None-Match": window.detag 
				}, 
				onSuccess: function(req) {
					var date = new Date(req.getHeader("Last-Modified"));
					var dnew = date.getTime();
					if (dnew <= window.dold) {
						req.responseText = $("sbmsglist").innerHTML;
					} else {
						window.dold = dnew;
						window.detag = req.getHeader("Etag");
						if (!window.firstCall) {
							Sound.enable();
							Sound.play("templates/builder/snd/newmsg.mp3", {
								replace: true
							});
							if ($("sb_panel-xcollapsed").visible() && $("sb_panel").hasClassName("x-panel-collapsed")) {
								new PeriodicalExecuter(function(pe) {
									if ($("sb_panel-xcollapsed").visible() && $("sb_panel").hasClassName("x-panel-collapsed")) {
										$("sb_panel-xcollapsed").toggleClassName("x-layout-collapsed-over");
									} else {
										pe.stop();
									}
								}, 1);
							}
						}
					}
					window.firstCall = false;
				},
				on304: function(req) {
					req.responseText = $("sbmsglist").innerHTML;
				}
			});
		}, 4);
		<? } ?>
		module = new Ext.tree.TreeNode({
			text: "Global",
			leaf: true,
			cls: "x-tree-node-collapsed",
			id: "-1",
			allowChildren: false
		});
		module.handlers = [];
		module.handlers.push(new Ext.tree.TreeNode({
			text: "home",
			leaf: true,
			id: "h_-1",
			allowChildren: false
		}));
		module.datas = [];
		Builder.root.appendChild(module);		
		<c:foreach var="modules" name="module">
			module = new Ext.tree.TreeNode({
				text: "#module.name",
				leaf: true,
				cls: "x-tree-node-collapsed",
				id: "#module.module_id",
				allowChildren: false
			});
			window.testsuites.push({text: "#module.name Tests", id: "#module.module_id"});
			module.handlers = [];
			<c:foreach var="module.handlers" name="handler">
				module.handlers.push({
					text: "#handler.event",
					leaf: true,
					cls: (<c:if cond="strlen($arr_param['handler']['hook'])>0">"handler-hook"<c:else/>null</c:if>),
					id: "h_#handler.handler_id",
					allowChildren: false
				});
			</c:foreach>
			module.datas = [];
			<c:foreach var="module.datas" name="data">
				var data = new Ext.tree.TreeNode({
					text: "#data.name",
					leaf: true,
					id: "d_#data.data_id",
					allowChildren: false
				});
				data.cls = "query";
				module.datas.push(data);
			</c:foreach>
			Builder.root.appendChild(module);
		</c:foreach>
		var addLibTree = function(root, entries) {
			for (var all in entries) {
				var children = !(entries[all] > 0);
				var node = new Ext.tree.TreeNode({
					text: all,
					leaf: !children,
					iconCls: !children ? "file" : "folder",
					allowChildren: children
				});
				root.appendChild(node);
				if (children) {
					if (typeof(entries[all]) != "function") {
						addLibTree(node, entries[all]);
					}
				}
			}
		};
		<c:foreach var="libraries" name="library">
			lib = new Ext.tree.TreeNode({
				text: "#library.name",
				leaf: ('#library.fk_resource_id' <= 0),
				iconCls: "library",
				id: "l_#library.library_id",
				allowChildren: ('#library.fk_resource_id' > 0)
			});
			<% if ($library["fk_resource_id"] > 0 && $library['resource']['resource_id'] > 0) { %>
				addLibTree(lib, (#library.resource.tree));
			<% } %>
			Builder.libRoot.appendChild(lib);
		</c:foreach>
		<c:foreach var="tags" name="tag">
			tag = new Ext.tree.TreeNode({
				text: "#tag.name",
				leaf: true,
				iconCls: "tagLib",
				id: "t_#tag.tag_id",
				allowChildren: false
			});
			Builder.tagRoot.appendChild(tag);
		</c:foreach>
		<c:foreach var="tables" name="table">
			table = new Ext.tree.TreeNode({
				text: "#table.name",
				leaf: true,
				iconCls: "table",
				id: "db_#table.table_id",
				allowChildren: false
			});
			Builder.dbRoot.appendChild(table);
		</c:foreach>		
		Builder.langRoot.createSubNode = function(nodeName, subNodes, parentNode) {
		    if (parentNode == Builder.langRoot) {
		      pid = "text_";
		    } else pid = parentNode.id;
			var expanded = false;
			if ("<?=$_GET['open_tree']?>".indexOf(nodeName+".") >= 0 || "<?=$_GET['open_tree']?>".indexOf("."+nodeName) >= 0) {
				expanded = true;
			}
	        var node = new Ext.tree.TreeNode({
	           text: nodeName,
			   expanded: expanded,
	           id: pid+"."+nodeName,
	           allowChildren: (typeof(subNodes) != "string"),
	           leaf: (typeof(subNodes) == "string"),
	           iconCls: (typeof(subNodes) == "string" ? "locale" : null),
	           listeners: {
	               dblclick: function(n) {
	                   if (n.isLeaf()) {
	                       // open that text...
	                       Builder.editText(n);
	                   }
	               }
	           }
	        });
	        node.subNodes = subNodes;
	        parentNode.appendChild(node);
	        if (subNodes && typeof(subNodes) != "string") {
    	        for (var each in subNodes) {
    	           if (typeof(subNodes[each]) != "function") {
    	               Builder.langRoot.createSubNode(each, subNodes[each], node);
    	           }
    	        }
	        }
	    }
		
		window.testsuites.push("-");
		window.testsuites.push({
			group: "",
			id: "view-log",
			text: "View Log",
			handler: window.__viewLog = function() {
				Ext.getCmp("view-log").setChecked(false);
				new Ext.Window({
					layout: "fit",
					title: "Test Log",
					modal: false,
					autoScroll: true,
					resizable: true,					
					shadow: true,
					width: 374,
					height: 360,
					plain: true,
					listeners: {
						close: function(p) {
							Ext.getCmp("view-log").setChecked(false);
						}
					},
					html: "<div class='testLog'>"+(window["testLog"] ? testLog.join("") : "No testsuite has been run.")+"</div>"					
				}).show();
			}
		});
		window.testsuites.push({
			group: "",
			id: "view-run",
			text: "View Test Run",
			handler: window.__viewRun = function() {
				Ext.getCmp("view-run").setChecked(false);
				window.__testTargetWindowContainer.show();
			}
		});
		
		window.userMgmtItems = [];
		<? if (($_SESSION["builder"]["group"] == "admin" || $_SESSION["builder"]["name"] == "admin")) { ?>
		userMgmtItems.push({
			text: "All Users",
			handler: function() {
				invoke(null, "builder:editUser", {getList: 1}, false, function(req) {
					showUserMgmt(req.responseText, "All Users");					
				});							
			}
		});
		<? } ?>
		userMgmtItems.push({
			text: "Edit Account",
			handler: function() {
				showUserMgmt();
			}
		});
		userMgmtItems.push({
			text: "Logout",
			handler: function() {
				location.href = "?event=builder:logout&norelogin=1";
			}
		});
					
		
		<c:foreach var="texts" name="text" key="section">
		    Builder.langRoot.createSubNode("#local.section", <?=json_encode($arr_param["text"])?>, Builder.langRoot);
		</c:foreach>
		window.Builder.isDeveloper = <?=$_SESSION["builder"]["group"] != "devel" ? "false" : "true"?>;
		window.Builder.isAdmin = <?=($_SESSION["builder"]["group"] == "admin" || $_SESSION["builder"]["name"] == "admin") ? "true" : "false"?>;
		window.Builder.productionEnvironment = <?=(ENV_PRODUCTION ? "true" : "false")?>;
		window.Builder.noRewrite = <?=MOD_REWRITE ? "false" : "true"?>;
		window.profilerLogs = <?=(file_exists("log/profiler_system.log") ? "true" : "false")?>;
		
		(function() {
			try {
				<c:hook name="builder-init"/>
			} catch(e) {
				window.console && console.log(e.message);
			}
		})();
		Builder.init('<?=$_GET["open_nav"]?>');
		<c:if cond="strlen($_GET['open_tree']) > 0">
			var l = Ext.getCmp("qwbuilder_langsPanel").getNodeById("text_.<?=$_GET['open_tree']?>");
			Builder.editText({ident: '<?=strtolower($_GET["open_tree"])?>', text: (l && l.text) || "New Text"});
		</c:if>
		window.document.body.observe("keydown", function(event) {
			var input = event.target.nodeName.toUpperCase() == "INPUT" || event.target.nodeName.toUpperCase() == "TEXTAREA";
			if (!input && (event.keyCode == 8 || (event.keyCode == 37 && (event.altKey || event.metaKey)))) {
				event.stop();
			}
		}).observe("keyup", function(event) {
			var input = event.target.nodeName.toUpperCase() == "INPUT" || event.target.nodeName.toUpperCase() == "TEXTAREA";
			if (!input && (event.keyCode == 8 || (event.keyCode == 37 && (event.altKey || event.metaKey)))) {
				event.stop();
			}
		});
	});
	//]]>
</script>